package com.mishow.activity;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.application.MyApplication;
import com.mishow.em.EMCustom;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.AuthCodeResponse;
import com.mishow.request.response.LoginResponse;
import com.mishow.request.result.User;
import com.mishow.service.LocationServices;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.ToastUtil;
import com.mishow.volley.http.request.FastJsonRequest;
/**
 * 
 * 作者：wei.miao <br/>
 * 描述：登录界面
 */
public class LoginActivity extends BaseActivity {
	/** 返回 **/
	private ImageView image_login_delete;
	
	/** 忘记密码 **/
	private TextView txt_login_forget_pwd;
	/** 登录 **/
	private Button btn_login;
	/** 获取验证码 **/
	private Button btn_get_authcode;
	
	/** 注册 **/
	private TextView text_login_register;
	/** 手机号码 **/
	private EditText edit_login_phone;
	
	/** 验证码**/
	private EditText edit_login_authcode;
	
	/** 
	 * 计时器任务
	 */
	private ScheduledExecutorService executorService;
	/**
	 * 获取验证码倒计时总时间
	 */
    private int totalTime = 60;
    /**
     * 倒计时正在进行
     */
    private final static int TIME_REMAIN = 0;
    /**
     * 倒计时结束
     */
    private final static int TIME_UP = 1;
    /**
     * 是否被踢下线
     */
    private boolean onlyLogin = false;
    
    private SharedPreferencesUtil mShPreferencesUtil;
    /** 登录账号 **/
    private String login_account;
    
    public static void intoActivity(Context context,int requestCode,int responseCode){
		
		Intent intent = new Intent(context,LoginActivity.class);
		intent.putExtra(Constants.LOGIN_RESPONSE_NAME, responseCode);
		((Activity)context).startActivityForResult(intent, requestCode);
		
	}
	@Override
	protected void initData() {

		mShPreferencesUtil = new SharedPreferencesUtil(mContext);
	}

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.activity_login);
		
		image_login_delete = (ImageView) findViewById(R.id.image_login_delete);
		
		txt_login_forget_pwd = (TextView)findViewById(R.id.text_login_forget_pwd);
		text_login_register = (TextView)findViewById(R.id.text_login_register);
		
		
		edit_login_phone = (EditText)findViewById(R.id.edit_login_phone);
		edit_login_authcode = (EditText) findViewById(R.id.edit_login_authcode);
		
		btn_get_authcode = (Button)findViewById(R.id.btn_get_authcode);
		btn_login = (Button)findViewById(R.id.btn_login);
	}

	@Override
	protected void setAttribute() {

		btn_get_authcode.setOnClickListener(onClickListener);
		btn_login.setOnClickListener(onClickListener);
		text_login_register.setOnClickListener(onClickListener);
		txt_login_forget_pwd.setOnClickListener(onClickListener);
		image_login_delete.setOnClickListener(onClickListener);
		// 自动获取并显示手机号
        //setLoginNum();
		
		/*if (mShPreferencesUtil.getLoginState()) {
			
			Intent intent = new Intent(LoginActivity.this, MainActivity.class);
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        startActivity(intent);
	        finish();
		}*/
	}
	
	private OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.btn_login:
				// 先将颜色展出铺满，然后启动新的Activity
				checkNumAndCode();
				break;
			case R.id.btn_get_authcode: //获取验证码
				if (!checkMobileNum()) {
                    return;
                }
				login_account = edit_login_phone.getText().toString().trim();
                // 获取短信验证码
                getSmsCode(login_account,"0");
				break;
			case R.id.text_login_register:
				  //CircularAnimUtil.startActivity(LoginActivity.this, RegisterActivity.class, v, R.color.colorPrimary);
				  startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
				  //LoginActivity.this.finish();
				break;
			case R.id.text_login_forget_pwd:
				  //CircularAnimUtil.startActivity(LoginActivity.this, ForgetPwdActivity.class, v, R.color.colorPrimary);
				startActivity(new Intent(LoginActivity.this, ForgetPwdActivity.class));
				break;
			case R.id.image_login_delete:
				back();
				break;
			default:
				break;
			}
		}
	};
	
	/**
	 * 手机号获取及显示
	 */
    private void setLoginNum() {
        // 从sp获取保存的手机号码
        String uName = mShPreferencesUtil.getLastAccount();
        // 手机号为空自动获取手机号
        if (TextUtils.isEmpty(uName)) {
            uName = AndroidUtil.getPhoneName(this);
        }
        // 手机号不为空
        if (!TextUtils.isEmpty(uName)) {// 显示手机号编辑框
            edit_login_phone.setText(uName);
            // TODO 三星机型（4.1.2）报IndexOutOfBoundsException异常
            try {
            	edit_login_phone.setSelection(uName.length());
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }
	/**
     * 检验输入的手机号和短信验证码的是否符合规格
     */
    private void checkNumAndCode() {
        // 检验手机号
        if (!checkMobileNum()) {
            return;
        }
        // 验证码
        String codeStr = edit_login_authcode.getText().toString().trim();
        // 验证码6位判断
        if (TextUtils.isEmpty(codeStr) || codeStr.length() < 6) {
            Toast.makeText(this, R.string.verify_code_error, Toast.LENGTH_SHORT).show();
            return;
        }
        // 联网请求登录
        doLoginRequest(edit_login_phone.getText().toString().trim(),codeStr,"0");
    }
	
	 /**
     * 验证手机号
     */
    private boolean checkMobileNum() {
        String mobileNum = edit_login_phone.getText().toString().trim();
        // 手机号为空
        if (TextUtils.isEmpty(mobileNum)) {
            Toast.makeText(this, R.string.verify_num_null, Toast.LENGTH_SHORT).show();
            return false;
        }
        // 判断手机号是否符合规范
        if (!AndroidUtil.isMobileNO(mobileNum)) {
            Toast.makeText(this, R.string.user_format_err, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
	
    /**
     * 获取手机短信验证码接口封装
     * @param mobile 手机号
     * @param sntype 短信类型(0-登录1-注册2-其他)
     */
    private void getSmsCode(String mobile,String sntype) {
        // 判断网络是否连接
        if (!AndroidUtil.isNetworkAvailable(mContext)) {
        	ToastUtil.show(mContext, getResources().getString(R.string.no_connector));
            return;
        }
        showProgress(null, null, false);
        Map<String, String> params = new HashMap<>();
        params.put("mobile", mobile);
        params.put("sntype", sntype);

        String getAuthCode_url = HttpUrlConstant.getPostUrl(mContext, HttpUrlConstant.GET_VERIFYCODE_STRING);
        Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mContext, params);
        OnResponseListener<AuthCodeResponse> listener = new OnResponseListener<AuthCodeResponse>(mContext) {

            @Override
            public void onSuccess(AuthCodeResponse response) {
                getCodeSuccess();
            }
            @Override
            public void onError(String code, String message) {
                dismissProgress();
                ToastUtil.show(mContext, message);
            }

            @Override
            public void onCompleted() {
                dismissProgress();
            }
        };
        
        executeRequest(new FastJsonRequest<AuthCodeResponse>(Method.POST,getAuthCode_url,AuthCodeResponse.class, listener,listener)
        		.setParams(lastParams));
        
        
        
    }
    
    /**
     * 获取验证码成功，开启倒计时
     */
    private void getCodeSuccess() {
        
        ToastUtil.show(mContext, getString(R.string.getcode_success_string));
        executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleWithFixedDelay(new CodeTimeTask(), 1, 1, TimeUnit.SECONDS);
        btn_get_authcode.setText(String.format(getString(R.string.count_down_re_verify), totalTime));
        btn_get_authcode.setTextColor(getResources().getColor(R.color.reset_time));
        btn_get_authcode.setEnabled(false);
    }
    
    /**
     * 停止计时
     */
    private void resetTime() {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
        btn_get_authcode.setEnabled(true);
        btn_get_authcode.setText(R.string.get_code_string);
        btn_get_authcode.setTextColor(getResources().getColor(R.color.white));
        totalTime = 60;
    }
    
    /**
     * 获取验证码倒计时Task
     */
    private class CodeTimeTask implements Runnable {
        @Override
        public void run() {
            totalTime--;
            // 更新重发时间
            if (totalTime > 0) {
                timeHandler.obtainMessage(TIME_REMAIN).sendToTarget();
            } else {
                timeHandler.obtainMessage(TIME_UP).sendToTarget();
            }
        }

    }

    /**
     * 发送验证码任务回调
     */
    private Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TIME_REMAIN:
                    btn_get_authcode.setText(String.format(getString(R.string.count_down_re_verify), totalTime));
                    break;
                case TIME_UP:
                    resetTime();
                    break;
                default:
                    break;
            }
        }

    };
    
    
	/**
	 * 登陆网络请求
	 * @param account 用户手机号
	 * @param authcode 验证码
	 * @param authType 登录方式0-手机登录 1-qq 2-微信 3-微博
	 */
	public void doLoginRequest(String account, String authcode,String authType) {
		//判断网络是否连接
		if (!AndroidUtil.isNetworkAvailable(this)) {
			Toast.makeText(this,R.string.no_connector, Toast.LENGTH_SHORT).show();
			return;
		}
		showProgress(null, null, true);
		Map<String, String> params = new HashMap<String, String>();
		
		params.put("userPhone", account);//手机号码
		params.put("snCode", authcode);//手机验证码
		params.put("authType", authType);//0-手机登录 1-qq 2-微信 3-微博
		params.put("userQq", "");//qq第三方uid
		params.put("userWeibo", "");//weibo第三方uid
		params.put("userWeixin", "");//weixin第三方uid
		params.put("userCname", "");//昵称
		params.put("userHead", "");//头像
		params.put("userInviteCode", "");//邀请码
		
		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(this, params);

		String url = HttpUrlConstant.getPostUrl(this, HttpUrlConstant.URL_LOGING);
		OnResponseListener<LoginResponse> listener = new OnResponseListener<LoginResponse>(this) {
			
			@Override
			public void onSuccess(LoginResponse response) {
				
				loginSuccess(response.getBody().getResult());
				mContext.finish();
			}
			
			@Override
			public void onError(String code, String message) {
				dismissProgress();
				ToastUtil.show(mContext,message);
			}
			
			@Override
			public void onCompleted() {
				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<LoginResponse>(Method.POST, url, LoginResponse.class, listener, listener).setParams(lastParams));
	}
	
	 /**
     * 登录成功
     */
    private void loginSuccess(User result) {
        dismissProgress();
        mShPreferencesUtil.setLoginState(true);
        // 用户手机号
        mShPreferencesUtil.setLoginfUserId(result.getUserId()+"");
        if (!TextUtils.isEmpty(result.getUserPhone())) {
        	mShPreferencesUtil.setLoginAccount(result.getUserPhone());
		}
        //由服务端注册
        //EMCustom.getInstance().EMCreateAccount(result.getUserId()+"",result.getUserPhone());
        
        EMCustom.getInstance().EMLogin(result.getUserId()+"",result.getUserPhone());
        
		ToastUtil.show(mContext, result.getUserPhone());
        if (onlyLogin) {
            // 返回首页
            MyApplication.toHomepage = true;
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }else{
        	setResult(RESULT_OK);
        }
        
    }
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
	}
	
	/**
     * 返回键，用于被踢下线时返回
     */
    private void back() {
        if (onlyLogin) {
            // 返回首页
            MyApplication.toHomepage = true;
            Intent intent = new Intent(mContext, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        this.finish();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
